import asyncio

import os
from dao.BaseRepository import BaseRepository
from loguru import logger
import pymongo
import re
import time
import json

baseRep = BaseRepository(collectionname="aishry")

import asyncio

from playwright.async_api import Playwright, async_playwright, expect, BrowserContext, Browser, Page


async def get_detail(context: Page, url: str):
    await context.goto(url)
    await context.wait_for_selector("span.meta-category")
    span = await context.query_selector_all("span.meta-category a")

    ele_h1 = await context.query_selector("h1.entry-title")
    game_name = await ele_h1.inner_text()
    _, num, msg = baseRep.search_no_page(
        {"name": game_name})
    if num > 0:
        logger.info(f"{game_name}已经存在,不用插入数据库")
        await context.wait_for_timeout(3000)
        return
    game_category = await span[0].inner_text()
    game_type = await span[1].inner_text()
    logger.debug(game_name)
    logger.debug(game_type)
    logger.debug(game_category)
    ele_p = await context.query_selector("div.entry-content p")
    game_desp = await ele_p.inner_text()
    logger.debug(game_desp)
    ele_p = await context.query_selector("span.meta-date time")
    game_update_time = await ele_p.inner_text()
    logger.debug(game_update_time)
    await context.get_by_role("link", name="点击下载").click()

    await context.wait_for_selector("textarea.form-control")
    await context.wait_for_timeout(3000)
    ele_text = await context.query_selector_all("div.panel-body")

    game_info = await ele_text[-1].inner_html()
    logger.debug(game_info)
    pattern = r"https://pan\.baidu\.com/s/\w+(?:\?pwd=\w{4})?"

    match = re.findall(pattern, game_info, flags=re.MULTILINE)
    logger.debug(match)

    if len(match) > 0:
        pan_url = match[0]
        pan_code = ""
        if "pwd=" in pan_url:
            pan_code = pan_url.split("pwd=")[-1]
        game = {
            "name": game_name,
            "description": game_desp,
            "pan_link": pan_url,
            "pan_code": pan_code,
            "status": "need_save",
            "update_time": game_update_time,

        }
        logger.info("当前游戏为:" + json.dumps(game, ensure_ascii=False))
        logger.info("插入数据库")
        baseRep.insert_one(game)
        await context.wait_for_timeout(300)


async def run(playwright: Playwright) -> None:
    browser = await playwright.chromium.launch(headless=False, slow_mo=300)
    if os.path.exists("state.json"):
        context = await browser.new_context(storage_state="state.json")
    else:
        context = await browser.new_context()
    page = await context.new_page()
    if not os.path.exists("state.json"):
        await page.goto("https://www.aishry.com/")
        await page.get_by_role("link", name=" 登录").click()
        await page.get_by_placeholder("*用户名或邮箱").fill("terrydash")
        await page.get_by_placeholder("*密码").fill("52Xuguoxu")
        await page.get_by_role("button", name=" 安全登录").click()
        await page.get_by_role("link", name="最新更新").click()
    await page.goto("https://www.aishry.com/?type=text&id=5")
    alinks = await page.locator("div.entry-content li a").all()
    logger.debug(len(alinks))

    for alink in alinks:
        url = await alink.get_attribute("href")
        logger.debug(url)
        await get_detail(page, url)
        # break

    # page1 = await page1_info.value
    # await page1.get_by_role("link", name="全部").nth(1).click()
    # async with page1.expect_popup() as page2_info:
    #     await page1.get_by_role("link", name="使命召唤17：黑色行动冷战/Call of Duty:").first.click()
    # page2 = await page2_info.value
    # await page2.goto("https://www.aishry.com/member/unlogin.php?type=fahuo&id=7208&genkey=20240102142117")
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").dblclick()
    # page2.once("dialog", lambda dialog: dialog.dismiss())
    # await page2.get_by_role("button", name="复制").click()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click(click_count=3)
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").dblclick()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click(button="right")
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click()
    # await page2.get_by_text("如需解压密码：XDGAME 百度：https://pan.").click()

    # ---------------------
    await context.close()
    await browser.close()


async def main() -> None:
    async with async_playwright() as playwright:
        await run(playwright)


asyncio.run(main())
